package model.towers;

import java.util.concurrent.CopyOnWriteArrayList;


import model.bullets.FrostBullet;
import model.bullets.RegularBullet;
import model.enemies.IEnemy;
import model.utils.PauseMenuDialog;
import model.utils.Sounds;

/**
 * Thread locates the closest enemy and start shooting till is dead or out of
 * range.
 * 
 * @author EvilTeam
 * 
 */
public class StartShootingThread implements Runnable {

	private ITower tower;
	private CopyOnWriteArrayList<IEnemy> enemies;
	private IEnemy tempEnemy;
	private volatile boolean isRunning = true;

	public StartShootingThread(ITower tower, CopyOnWriteArrayList<IEnemy> enemy) {
		this.tower = tower;
		this.enemies = enemy;
	}

	@Override
	public void run() {
		while (isRunning) {
			boolean shotOnce = false;
			for (IEnemy enemy : enemies) {
				if (enemy != null && enemy.getHealthPoints() > 0
						&& tower.inRange(enemy)) {
					if (tempEnemy == null || !tower.inRange(tempEnemy)
							|| tempEnemy.getHealthPoints() <= 0) {
						tempEnemy = enemy;
					}
					if (!shotOnce) {
						if (PauseMenuDialog.isMute())
							Sounds.playSoundOnShoot();
						tower.update();
						if (tower instanceof FireTower) {
							tower.addBullet(new RegularBullet(tower
									.getxAxisPoint(), tower.getyAxisPoint(),
									FireTower.FIRE_BULLET, tempEnemy, tower
											.getDamage()));
						}
						if (tower instanceof FrostTower) {
							tower.addBullet(new FrostBullet(tower
									.getxAxisPoint(), tower.getyAxisPoint(),
									tempEnemy, ((FrostTower) tower).getSlow()));
						}
						if (tower instanceof LaserTower) {
							tower.addBullet(new RegularBullet(tower
									.getxAxisPoint(), tower.getyAxisPoint(),
									LaserTower.LASER_BULLET, tempEnemy, tower
											.getDamage()));
						}
						shotOnce = true;
					}

					if (tempEnemy.getHealthPoints() <= 0
							|| !tower.inRange(tempEnemy)) {
						tempEnemy = null;
					}
				}
			}
			try {
				Thread.sleep(((TowerSprite) tower).getShootingSpeed() * 1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public void stopShooting() {
		isRunning = false;
	}
}
